
package com.hs.log;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 * This class extends the {@link java.util.logging.Formatter} class to format
 * log messages.
 *
 * @see org.jamwiki.utils.HsLogger
 */
public class HsLogFormatter extends Formatter {

	private static final String SEPARATOR = System.getProperty("line.separator");
	private final String datePattern;

	/**
	 *
	 */
	public HsLogFormatter(String datePattern) {
		super();
		this.datePattern = datePattern;
	}

	/**
	 *
	 */
	public String format(LogRecord record) {
		StringBuffer buffer = new StringBuffer();
		SimpleDateFormat formatter = new SimpleDateFormat(datePattern);
		buffer.append(formatter.format(new Date(record.getMillis())));
		buffer.append(' ');
		buffer.append(record.getLevel().getName());
		buffer.append(": ");
		buffer.append(record.getLoggerName());
		buffer.append(" - ");
		buffer.append(formatMessage(record));
		buffer.append(SEPARATOR);
		Throwable throwable = record.getThrown();
		if (throwable != null) {
			StringWriter sw = new StringWriter();
			throwable.printStackTrace(new PrintWriter(sw, true));
			buffer.append(sw.toString());
		}
		return buffer.toString();
	}
}
